package net.fltx.assets.filter;

import net.fltx.assets.entity.AccessLog;
import net.fltx.assets.service.AccessLogService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;

public class AccessLogFilter implements Filter {

    @Autowired
    private AccessLogService accessLogService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //System.out.println(accessLogService);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        AccessLog accessLog = new AccessLog();

        String tmp = request.getRemoteAddr();
        if (tmp != null && tmp.length() > 128) {
            tmp = tmp.substring(0, 128);
        }
        accessLog.setIp(tmp);

        tmp = URLDecoder.decode(request.getRequestURI(), "utf-8");
        if (tmp != null && tmp.length() > 512) {
            tmp = tmp.substring(0, 512);
        }
        accessLog.setUri(tmp);

        tmp = request.getHeader("USER-AGENT");
        if (tmp != null && tmp.length() > 255) {
            tmp = tmp.substring(0, 255);
        }
        accessLog.setUserAgent(tmp);

        tmp = request.getHeader("Accept-Language");
        if (tmp != null && tmp.length() > 255) {
            tmp = tmp.substring(0, 255);
        }
        accessLog.setAcceptLanguage(tmp);

        try {
            accessLogService.insert(accessLog);
        } catch (Exception e) {
            System.out.println(accessLog);
            System.out.println(e);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
